import UIKit
import SDWebImage

typealias ImageTapGestureBlock = () -> (UIImage)
protocol TF_BackChatUrlDelegate: class {
    func urlClick(url:String)
}
class TF_BackChatCell: UITableViewCell,UITextViewDelegate {
    var bgView:UIView!
    var avatarImageView:UIImageView!
    var nameAndmsgLab:UILabel!
    var cellwidth:CGFloat = 0
    var isOrientationLandscape:Bool = false //yes 横屏; no 竖屏

    var content:TF_StoyCopyTextView!

    var image:UIImageView!
    var imageUrlView:TF_BackImagePreviewView!
    var imageUrl:String!

    var cellGestueBlock: ((UIImage) -> ())?
    weak var urldelegate: TF_BackChatUrlDelegate?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = UIColor.clear
        
       
        self.bgView = UIView.init()
        self.bgView.backgroundColor = UIColor.white
        self.bgView.layer.cornerRadius = 14
        self.bgView.layer.masksToBounds = true
        self.contentView.addSubview(self.bgView)
        
        self.avatarImageView = UIImageView.init()
        self.avatarImageView.layer.masksToBounds = true;
        self.avatarImageView.layer.cornerRadius = 10;
        self.bgView.addSubview(self.avatarImageView)
        
        //聊天内容
        self.content = TF_StoyCopyTextView.init()
        self.content.backgroundColor = UIColor.clear
        self.content.isScrollEnabled = false;
        self.content.textContainer.lineFragmentPadding = 0;
        self.content.textContainerInset =  UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.content.isEditable = false
        self.content.font = UIFont.systemFont(ofSize: 14)
        self.content.delegate = self;
        self.bgView.addSubview(self.content)
        
        self.image = UIImageView.init()
        self.image.backgroundColor = UIColor.clear
        self.image.isUserInteractionEnabled = true
        self.bgView.addSubview(self.image)
        self.image.contentMode = .scaleToFill
            
            
        let singleRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(dealSingleTap))
   
        /*单击    -------    点击的次数*/
        singleRecognizer.numberOfTapsRequired = 1;
        self.image.addGestureRecognizer(singleRecognizer)
       
    }
    
    @objc func dealSingleTap()  {
        let keyWindow = TalkfunSharedTools.keyWindow()
        
        self.imageUrlView = TF_BackImagePreviewView.init()
        keyWindow.addSubview(self.imageUrlView)
 
        self.imageUrlView.frame = TalkfunSharedTools.getMainScreen()
      
        self.imageUrlView.layoutSubviewsUI(imageUrl: self.imageUrl)
      
    }
    
    
    func setBackmodel(model:TF_BackChatLiveData) {
       
        let nickNamecolor:UIColor
        let msgColor:UIColor
    
        if (self.isOrientationLandscape) {
            self.bgView.backgroundColor =  UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.8)
            nickNamecolor = UIColor(red: 65/255.0, green: 150/255.0, blue: 235/255.0, alpha: 1.0)
            msgColor = UIColor.white
        } else {
            self.bgView.backgroundColor = UIColor.white
            nickNamecolor = UIColor(red: 150/255.0, green: 160/255.0, blue: 170/255.0, alpha: 1.0)
            msgColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1.0)
          
        }
            var roleStr:String = ""
              
            if (model.role == .roleSpadmin) {
                    roleStr = "老师";
        
                }
                //=============== 如果是助教说的话 =================
        else if (model.role == .roleAdmin)
                {
                    roleStr = "助教";

                }
        self.avatarImageView.layer.cornerRadius = 10
        self.avatarImageView.sd_setImage(with: NSURL.init(string: model.avatar) as URL?, placeholderImage: UIImage.init(named: "HTLive.bundle/PlaceholderMap"), options: .retryFailed, context: nil, progress: nil, completed: nil)
      
       
        if (model.imageURL.count>0) { //
            model.msg = "";
            self.imageUrl = model.imageURL
        } else {
            model.msg = model.msg
        }
        let nickname = model.nickname + " "
        let str:NSString = nickname + model.msg as NSString
        
        let contentDict:[AnyHashable:Any]? = TalkfunSharedTools.assembleAttributeString(str as String, boundingSize: CGSize(width: self.cellwidth-35-16-12-16, height: 2000), fontSize: 14, shadow: false) as? [AnyHashable : Any]
     
        let attr:NSAttributedString = contentDict?["attributeStr"] as! NSAttributedString
       
        let AttributedString = NSMutableAttributedString.init(attributedString: attr)
        
        let attr33: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: msgColor,]
        AttributedString.addAttributes(attr33, range: NSRange(location: 0, length: attr.length))
        let attr34: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: nickNamecolor,]
        AttributedString.addAttributes(attr34, range: NSRange(location: 0, length: model.nickname.count))

        if roleStr.count > 0 {
    
            let attch = NSTextAttachment.init()
            if model.role == .roleAdmin { //助教
                attch.image = UIImage.init(named: "HTLive.bundle/chat_tag_assistant")
            } else if (model.role == .roleSpadmin) {//老师
                attch.image = UIImage.init(named: "HTLive.bundle/chat_tag_teacher")
            }
           
            attch.bounds = CGRect(x: 0, y: -3, width: 27, height: 15)
            let imageStr = NSAttributedString.init(attachment: attch)
            AttributedString.insert(imageStr, at: model.nickname.count+1)
            let Attri = NSAttributedString.init(string: " ")
            AttributedString.insert(Attri, at: model.nickname.count+2)
            let AttributeName: [NSAttributedString.Key : Any] = [.kern:5]
            AttributedString.addAttributes(AttributeName, range: NSRange(location: model.nickname.count+2, length: 1))
            
        
            
          
        }
        let font:UIFont? = UIFont.systemFont(ofSize: 14)
        
       
        let size =  TalkfunSharedTools.sizeLabelToFit(AttributedString, width: self.cellwidth-35-16-12-16, fontSize: font!)
      

        if (model.imageURL.count>0) {  //发送图片
            var imageHight:CGFloat = 96;
            var imageWidth:CGFloat = 96;
            var bgY:CGFloat = 0;
            if (self.isOrientationLandscape) {
                 imageHight = 68;
                imageWidth = 68;
                bgY = 4
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
            } else {
                imageHight = 96;
                imageWidth = 96;
                bgY = 8
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
            }
            if (model.image != nil) {
                if model.image.size.width == model.image.size.height {
                    self.image.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: self.content.frame.maxY+6, width: imageWidth, height: imageHight)
                } else if (model.image.size.width > model.image.size.height) {
                    
                    let proportion:CGFloat = model.image.size.width / imageWidth;
                    imageHight = model.image.size.height / proportion;
                    self.image.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: self.content.frame.maxY+6, width: imageWidth, height: imageHight)
                 
                } else if (model.image.size.width < model.image.size.height) {
                    let proportion:CGFloat = model.image.size.height / imageHight
                    let imagew:CGFloat = model.image.size.width / proportion
                    self.image.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: self.content.frame.maxY+6, width: imagew, height: imageHight)
                   
                }
            
                self.image.image = model.image;
            } else {
                
                
                self.image.image = UIImage.init(named: "HTLive.bundle/")
                
                let imageurl:URL? = URL.init(string: model.imageURL)

                let imageManage = SDWebImageManager.shared
                imageManage.loadImage(with: imageurl, options: SDWebImageOptions.retryFailed) { receivedSize, expectedSize, targetURL in

                } completed: {[weak self] image, data, error, cacheType, finished, imageURL in
                    guard let `self` = self else {
                        return
                    }

                    DispatchQueue.main.async {


                        if (image != nil)  {
                            
                            model.image = image!
                            if (self.cellGestueBlock != nil) {
                                self.cellGestueBlock?(model.image)
                            }
                        }

                    }
                }
            }
       

          
            if (size.width > self.image.frame.size.width) {
                 
                self.bgView.frame = CGRect(x: 12, y: bgY, width: 34+size.width+8, height: self.image.frame.maxY+8)
            } else {
                self.bgView.frame = CGRect(x: 12, y: bgY, width: self.image.frame.maxX+8, height: self.image.frame.maxY+8)
          
            }

        } else {
            self.image.image = nil;
            self.image.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
            if (self.isOrientationLandscape) {
                self.bgView.frame = CGRect(x: 12, y: 4, width: size.width+16+35, height: size.height+12)
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
              

            } else {
                self.bgView.frame = CGRect(x: 12, y: 8, width: size.width+16+35, height: size.height+12)
                self.avatarImageView.frame = CGRect(x: 6, y: 6, width: 20, height: 20)
                self.content.frame = CGRect(x: self.avatarImageView.frame.maxX+8, y: 6, width: size.width, height: size.height)
      
            }
        }

        self.content.addHyperlink(font: font!, attributedText: AttributedString)
        self.content.attributedText = AttributedString;
      
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



